package com.jiuyin.dianjing.ui.activity.community;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.UniversityClub;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.ui.fragment.community.CollegesListFragment;
import com.jiuyin.dianjing.ui.fragment.community.PostFragment;
import com.jiuyin.dianjing.util.DisplayUtil;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ShareUtil;
import com.jiuyin.dianjing.util.ToastUtil;
import com.jiuyin.dianjing.view.ExpandTextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ATTENTION_MODEL;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ATTENTION_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ISATTENTION;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TARGETID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.VALUE_ATTENTION_CLUB;
import static com.jiuyin.dianjing.api.constant.ApiConstant.VALUE_GENRE_COLLEGES;
import static com.jiuyin.dianjing.api.constant.ApiConstant.VALUE_TYPE_HOT;
import static com.jiuyin.dianjing.ui.activity.community.TagActivity.KEY_DESIRE_TAG;
import static com.jiuyin.dianjing.ui.activity.community.TagActivity.KEY_GAME_TAG;

public class CollegeMainActivity extends BaseActivity {
    @BindView(R.id.tv_watch)
    CheckedTextView tvWatch;
    @BindView(R.id.tv_join)
    TextView tvJoin;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_member_count)
    TextView tvMemberCount;
    @BindView(R.id.tv_watch_num)
    TextView tvWatchCount;
    @BindView(R.id.tv_intro)
    ExpandTextView tvIntro;
    @BindView(R.id.tv_hot_tag)
    TextView tvHotTag;

    private UniversityClub club;

    private String gameTag;
    private String desireTag;
    public static final int REQUEST_TAG_CHOOSE = 89;
    private PostFragment postFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_college_main;
    }

    @Override
    protected void initData() {
        club = (UniversityClub) getIntent().getSerializableExtra("UniversityClub");
        if (club == null) {
            finish();
        }
    }

    @Override
    protected void initView() {
        setTitle(club.name);
        setRightButton(R.drawable.img_share, v -> {
            toShare();
        });
        tvName.setText(club.name);
        tvIntro.setContent(club.intro);
        tvMemberCount.setText(String.valueOf(club.member_num));
        tvWatchCount.setText(String.valueOf(club.fans_num));
//        if (club.isJoin == 1) {
//            tvJoin.setVisibility(View.GONE);
//        } else if (club.isJoin == 0) {
//            tvJoin.setVisibility(View.VISIBLE);
//        } else {//2 申请中
//            tvJoin.setVisibility(View.VISIBLE);
//            tvJoin.setText("申请中");
//            tvJoin.setEnabled(false);
//        }
        if (club.isAttention == 1) {
            tvWatch.setText("已关注");
            tvWatch.setChecked(true);
        } else {
            tvWatch.setText("关注");
            tvWatch.setChecked(false);
        }

        Glide.with(this)
                .load(club.circle_logo)
                .override(DisplayUtil.dp2px(this, 50))
                .into(ivHead);
        postFragment = PostFragment.newInstance(VALUE_TYPE_HOT, VALUE_GENRE_COLLEGES, club.universityclub_id, null, null);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_post, postFragment)
                .commit();

    }

    @OnClick({R.id.tv_join, R.id.tv_watch, R.id.tv_whole_tag})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_join:
                //todo 加入电竞社
                Bundle bundle = new Bundle();
                bundle.putSerializable("clubModel", club);
                goTargetActivity(JoinEsportsClubActivity.class, bundle);
                break;
            case R.id.tv_watch:
                watch();
                break;
            case R.id.tv_whole_tag:
                Intent intent = new Intent(CollegeMainActivity.this, TagActivity.class);
                intent.putExtra(KEY_GAME_TAG, gameTag);//将当前选中的标签传给TagActivity,回显
                intent.putExtra(KEY_DESIRE_TAG, desireTag);
                startActivityForResult(intent, REQUEST_TAG_CHOOSE);
                break;
        }
    }

    private void toShare() {
        ShareUtil shareUtil = ShareUtil.getInstance(CollegeMainActivity.this, club.list_logo, club.name);
//        if (postModel.getPhoto().size() > 0) {
//            shareUtil.setImageUrl(postModel.getPhoto().get(0));
//        }
        shareUtil.initShare();
        shareUtil.open();
    }

    private void watch() {
        HashMap<String, Object> map = new HashMap<>();
        map.put(KEY_TOKEN, HelperApplication.getToken());
        map.put(KEY_TARGETID, club.universityclub_id);//被关注的主键
        map.put(KEY_TYPE, tvWatch.isChecked() ? 0 : 1);//（0 取消关注 1关注）
        map.put(KEY_ATTENTION_MODEL, VALUE_ATTENTION_CLUB);
        JSONObject json = new JSONObject(map);
        ApiResultCallback apiResultCallback = new ApiResultCallback() {
            @Override
            public void onSuccess(JsonObject data) {
                tvWatch.setEnabled(true);
                boolean isAttention = data.get(KEY_ISATTENTION).getAsInt() == 1;
                if (data.has(KEY_ATTENTION_NUM)) {
                    String newCom = data.get(KEY_ATTENTION_NUM).getAsString();
                    tvWatchCount.setText(newCom);
                }
                tvWatch.setChecked(isAttention);
                if (tvWatch.isChecked()) {
                    tvWatch.setText("已关注");
                } else {
                    tvWatch.setText("关注");
                }
                EventBus.getDefault().post(new RefreshEvent(CollegesListFragment.class.getSimpleName()));
            }

            @Override
            public void onFail(String msg) {
                tvWatch.setEnabled(true);
                ToastUtil.showShort(msg);
            }

            @Override
            public void onError(String msg) {
                tvWatch.setEnabled(true);
                LogUtil.log(msg);
            }
        };
        tvWatch.setEnabled(false);
        ServerApi.post(ApiEnum.APP_ADD_ATTENTION_LOG.getUrl(), json, null,
                progress, d -> addDisposable(d), apiResultCallback);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshEvent event) {
        if (event.clazzName.equals(getClass().getSimpleName())) {
            // TODO: 2020/5/14
//            tvJoin.setText("申请中");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_TAG_CHOOSE) {
                if (data == null) {
                    return;
                }
                gameTag = data.getStringExtra(KEY_GAME_TAG);
                desireTag = data.getStringExtra(KEY_DESIRE_TAG);
                StringBuilder stringBuilder = new StringBuilder();
                if (!TextUtils.isEmpty(desireTag)) {
                    stringBuilder.append(getString(R.string.tag, desireTag)).append("    ");
                }
                if (!TextUtils.isEmpty(gameTag)) {
                    stringBuilder.append(getString(R.string.tag, gameTag));
                }
                postFragment.setGenreTag(desireTag);
                postFragment.setGameTag(gameTag);
                if (TextUtils.isEmpty(stringBuilder.toString())) {
                    tvHotTag.setText(R.string.hot_labels);
                } else {
                    tvHotTag.setText(stringBuilder.toString());
                }
                postFragment.refresh();
            }
        }
    }
}
